/*
 * Copyright (c) 2013, SRI International
 * All rights reserved.
 * Licensed under the The BSD 3-Clause License;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 * 
 * http://opensource.org/licenses/BSD-3-Clause
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of the aic-web-praise nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.sri.ai.lpitools.gwtgui.client.components.dialogs;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.cell.client.EditTextCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CaptionPanel;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.sri.ai.lpitools.cobra.gwtutil.dataobjects.shared.EvidenceInfo;
import com.sri.ai.lpitools.gwtgui.client.RPCService;
import com.sri.ai.lpitools.gwtgui.client.RPCServiceAsync;
import com.sri.ai.lpitools.gwtgui.client.components.manager.ModelManager;
import com.sri.ai.lpitools.gwtgui.client.components.manager.UserManager;
import com.sri.ai.lpitools.gwtgui.client.util.JSONUtil;
import com.sri.ai.lpitools.gwtgui.client.view.EvidenceView;

public class EvidenceManagerPanel extends DockLayoutPanel implements EvidenceView {
	
	private UserManager userManager;
	private RPCServiceAsync rpc;
	private CaptionPanel listSelectPanel;
	private EvidenceEditPanel editPanel;
	
	
	//UI components
	private final SingleSelectionModel<String> selectionModel;
	private final CellList<String> evidenceList;
	private List<String> values;

	private List<String> evidences;
	
	public EvidenceManagerPanel(UserManager userManager) {
		super(Unit.EM);
		final Image image = new Image("images/loading_circle.gif");
		this.rpc = RPCService.Util.getInstance();
		this.userManager = userManager;
		//don't edit the text cells
		EditTextCell clickIgnorer = new EditTextCell() {
			@Override
			public void onBrowserEvent(Context context, Element parent, String value,
					NativeEvent event, ValueUpdater<String> valueUpdater) {
				String type = event.getType();
				if ("click".equals(type)) {
					return;
				}
				super.onBrowserEvent(context, parent, value, event, valueUpdater);
			}
		};
		//build the dialog guts
		selectionModel = new SingleSelectionModel<String>();
		evidenceList = new CellList<String>(clickIgnorer);
		evidenceList.setSelectionModel(selectionModel);
		evidenceList.setEmptyListWidget(image);
		evidenceList.setRowCount(0, true);
		
		
		
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		// events based upon user selection
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			
			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				String selection = selectionModel.getSelectedObject();
				if (selection != null) {
					openEditor(selection);
				} else {
					//do nothing
				}
			}
		});

		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		//perform component layout
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		SplitLayoutPanel splitLayoutPanel = new SplitLayoutPanel(5);
		LayoutPanel westLP = new LayoutPanel();
		
		final Button newEvidenceButton = new Button("New");
		newEvidenceButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				newEvidence();
			}
		});
		final Button deleteEvidenceButton = new Button("Delete");
		deleteEvidenceButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				String selection = selectionModel.getSelectedObject();
				if (selection != null) {
					deleteEvidence(selection);
				}
			}
		});
		
		westLP.add(newEvidenceButton);
		westLP.add(deleteEvidenceButton);
		
		westLP.setWidgetTopHeight(newEvidenceButton, 85, Unit.PCT, 10, Unit.PCT);
		westLP.setWidgetTopHeight(deleteEvidenceButton, 85, Unit.PCT, 10, Unit.PCT);
		westLP.setWidgetLeftWidth(newEvidenceButton, 10, Unit.PCT, 35, Unit.PCT);
		westLP.setWidgetRightWidth(deleteEvidenceButton, 10, Unit.PCT, 35, Unit.PCT);
		
		listSelectPanel = new CaptionPanel("Evidences");
		listSelectPanel.add(evidenceList);
		
		westLP.add(listSelectPanel);
		westLP.setWidgetTopHeight(listSelectPanel, 0, Unit.PCT, 85, Unit.PCT);
		
		splitLayoutPanel.addWest(westLP, 256);
		
		editPanel = new EvidenceEditPanel(true){

			@Override
			protected void saveEvidence() {
				EvidenceManagerPanel.this.saveEvidence(getEvidenceTitle(), getEvidence());
			}

			@Override
			protected void onCancel() {
				close();
			}};
		splitLayoutPanel.add(editPanel);
		
		splitLayoutPanel.setSize("512px", "256px");
		add(splitLayoutPanel);
		
		//request the list of queries from RPC
//		populateList();
		
	}
	
	public void setObjects(ModelManager modelM, UserManager userM, RPCServiceAsync rpcService) {
	
		
		
	}

	protected void populateList() {
		rpc.getEvidenceList(userManager.getCurrentUser().getUser(), new AsyncCallback<String>() {
			List<String> evidences = new ArrayList<String>();
			List<String> values = new ArrayList<String>();
			@Override
			public void onSuccess(String evidenceListString) {
				if (evidenceListString == null) {
					MessageDialog.showMessageDialog("Null response for getEvidenceList call.");
					close();
				}
				if(evidenceListString.startsWith("ERROR.")){
					evidences.add(evidenceListString);
				} else {
					List<EvidenceInfo> list = JSONUtil.getEvidenceInfoList(evidenceListString);
					for(EvidenceInfo current: list){
						evidences.add(current.getEvidenceTitle());
						values.add(current.getEvidenceTitle() + ":" + current.getEvidence());
					}
				}
				setEvidences(evidences, values);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				MessageDialog.showMessageDialog(caught.getMessage());
				close();
			}
		});
	}
	
    native  public static void close()/*-{  $wnd.close();
    }-*/;
    
	public void update(){
		populateList();
	}	
	
	protected void openEditor(String evidenceTitle) {
		editPanel.setEvidenceTitle(evidenceTitle);
		String evidenceValue = "";
		for(String info : values)
		{
			if(info.startsWith(evidenceTitle + ":"))
			{
				String[] split = info.split(":");
				evidenceValue = split[1];
			}
		}
		editPanel.setEvidence(evidenceValue);
	}

	/**
	 * populate the list with evidences, replacing the UI components
	 * @param queries
	 */
	public void setEvidences(List<String> evidences, List<String> values) {		
		evidenceList.setRowData(evidences);
		this.values = values;
		this.evidences = evidences;
	}
	
	protected void newEvidence() {

//		EvidenceInfo query = new EvidenceInfo(userManager.getCurrentUser().getUser(), "New Evidence", "");
//		
//		SingleEvidenceEditDialog dialog = new SingleEvidenceEditDialog(query, userManager, "New Evidence");
//		dialog.setEditor(this);
//		dialog.show();
//		dialog.center();
//		//MessageDialog.showMess
	}
	
	protected void deleteEvidence(String evidenceTitle) {
		MessageDialog.showMessageDialog("Deletion of " + evidenceTitle +" requested.");
	}
	
	protected void saveEvidence(String evidenceTitle, String evidence) {
		MessageDialog.showMessageDialog("Save of " + evidenceTitle + ":" + evidence +" requested.");
	}

	@Override
	public void setObjects() {
		update();
	}	
	
}
